package core.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * @author songduk park
 * 
 */
public class StringUtil {

	NumberFormat format32 = new DecimalFormat("#,###.00");
	NumberFormat format30 = new DecimalFormat("#,###");

	public static boolean isBlank(String str) {
		if (str == null || str.length() == 0)
			return true;
		return false;
	}

	public String formatNumber3_2(Object obj) {
		if (obj == null)
			return "";

		return format32.format(obj);
	}

	public String formatNumber3_0(Object obj) {
		if (obj == null)
			return "";

		return format30.format(obj);
	}

	public String nullToBlank(String str) {
		if (str == null)
			return "";
		return str;
	}

	public Object nullToBlank(Object obj) {
		if (obj == null)
			return "";
		return obj;
	}

	public String nullTo(String str, String val) {
		if (isBlank(str))
			return val;

		return str;
	}

	public static int getInteger(final String value) {
		try {
			if (value != null && value.indexOf(",") > -1) {
				return Integer.parseInt(value.replaceAll(",", ""));
			}
			return Integer.parseInt(value);
		} catch (Exception e) {
			return 0;
		}
	}

	public int getInt(final String value) {
		try {
			if (value != null && value.indexOf(",") > -1) {
				return Integer.parseInt(value.replaceAll(",", ""));
			}
			return Integer.parseInt(value);
		} catch (Exception e) {
			return 0;
		}
	}

	public String within(String str, int length, String tail) {
		if (str == null)
			return "";

		if (str.length() > length)
			return str.substring(0, length) + tail;

		return str;
	}

	public static String convertNumber(String str) throws Exception {
		if (str == null)
			return "0";

		str = str.trim();

		if (str.startsWith("(") && str.endsWith(")"))
			str = "-" + str;

		StringBuffer sb = new StringBuffer();

		char[] ch = str.toCharArray();
		for (char c : ch) {
			if (c != ' ' && c != ',' && c != '$' && c != '(' && c != ')')
				sb.append(c);
		}

		String result = sb.toString();

		try {
			Double value = Double.parseDouble(result);

			NumberFormat format = new DecimalFormat("#.##");
			return format.format(value);
		} catch (Exception e) {
			throw e;
		}
	}

	public static String convertTwoDigits(String str) {
		if (str == null || str.length() == 0)
			return "0";

		try {
			int num = Integer.parseInt(str);

			if (num > 0 && num < 10)
				return "0" + num;

		} catch (Exception e) {
		}
		return str;
	}
}
